'''
太平关爱今生重疾保障计划
'''
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太平关爱今生重疾保障计划"
    # 生成产品数据
    def genProductInfo(self):

        # 年缴计划

        plan_year = {

            "planA": {
                # 年龄段 45 - 59
                "year": [str(i) for i in range(0, 10)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5,25,5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["10","15","20"]
            },
            "planB": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(10, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5,45,5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["10", "15","20"]
            },
            "planC": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5, 45, 5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["10","15"]
            },
            "planD": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(46, 50)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5, 45, 5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["10"]
            },
        }

        for x in plan_year:

            for v in product(plan_year[x]["year"], plan_year[x]["gender"], plan_year[x]["money"],
                             plan_year[x]["expire"], plan_year[x]["payType"], plan_year[x]["interval"]):
                # 写入数据库
                # 写入数据库
                self.mysql.cursor.execute(
                    domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))

        # 月缴计划
        plan_month = {

            "planA": {
                # 年龄段 45 - 59
                "year": [str(i) for i in range(0, 10)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5,25,5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["月缴"],
                # 缴费间隔 10 120个月 15 180个月 20 240个月
                "interval": ["10","15","20"]
            },
            "planB": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(10, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5,45,5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["月缴"],
                # 缴费间隔 120个月 15 180个月 20 240个月
                "interval": ["10", "15","20"]
            },
            "planC": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5, 45, 5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["月缴"],
                # 缴费间隔 120个月 15 180个月 20 240个月
                "interval": ["10","15"]
            },
            "planD": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(46, 50)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5, 45, 5)],
                # 保障期限
                "expire": ["88周岁"],
                # 缴费方式
                "payType": ["月缴"],
                # 缴费间隔 120个月 15 180个月 20 240个月
                "interval": ["10"]
            },
        }
        for x in plan_month:

            for v in product(plan_month[x]["year"], plan_month[x]["gender"], plan_month[x]["money"],
                             plan_month[x]["expire"], plan_month[x]["payType"], plan_month[x]["interval"]):
                # 写入数据库
                # 写入数据库
                self.mysql.cursor.execute(
                    domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))

    #执行爬虫
    def requestJson(self,dt=None):

        if dt["payType"] == "年缴":

            print("~~~~~年缴~~~~~")
        else:

            print("~~~~~月缴~~~~~")

        code = self.filterProductCode( dt )

        data = {
            "pageName": "productAdd",
            "goods_id": "61876",
            "merchant_id": "B2C",
            "toubaoli_money":"",
            "productCode": code["productCode"],
            "productId": "e62babb3 - 2b8a - 4afb - 96c3 - cad02f9a65d6",
            "riskCode": code["riskCode"],
            "productName": "太平关爱今生重疾保障计划",
            "insuredPrice": "90.1",
            "insured.birthday":"",
            "templateType": "1",
            "employee_id":"",
            "channel": "GWSC - MENU - M12",
            "empNo":"",
            "newsCode":"",
            "twoMonthInsuredPrice": "180.20",
            "loginUserId":"",
            "insured.age": "0" + dt["year"] if int(dt["year"]) < 10 else dt["year"],
            "insured.sex": "1" if dt["gender"] == "M" else "2",
            "policy.amount": "05" if  dt["money"][:2] == "5" else dt["money"][:2],
            "policy.dateRemark": "88Y",
            "policy.chargeType": "1" if dt["payType"] == "年缴" else "4",
            "policy.chargeYear": dt["interval"],
            "person.mobilenum": "承保短信将发送至您的手机",
            "policy.showMessage": "true",
        }

        print(data)

        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "计算保费成功" in r.text:

            price = Helper.decimalParse( r.json()["totalPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("/*产品价格更新失败:%d*/"% dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

    #过滤产品代码
    def filterProductCode(self,dt=None):

        if dt["payType"] == "年缴" or dt["payType"] == "月缴":

            if dt["interval"] == "10":

                data = {
                    "productCode":"50000805",
                    "riskCode":"1000000005"
                }
                return data

            elif dt["interval"] == "15":
                data = {
                    "productCode": "50000806",
                    "riskCode": "1000000006"
                }
                return data
            else:
                data = {
                    "productCode": "50000807",
                    "riskCode": "1000000007"
                }
                return data

